<template>
	<view>
		<view class="container" :style="'padding-top: ' + (navbar.top + navbar.height + 6) + 'px'">

			<!-- #ifdef MP-WEIXIN -->
			<view class="navbar" :style="'height: ' + (navbar.top + navbar.height + 6) + 'px;'">
				<view class="inner">
					<view class="search_box"
						:style="'top:' + navbar.top + 'px;height: ' + navbar.height + 'px;width:'+(navbar.customWidth?navbar.customWidth:267)+'px;left:'+(navbar.marginLeft?navbar.marginLeft:17)+'px;'">
						<view class="por_search">
							<view class="poa_scan" :style="'height: ' + navbar.height + 'px'">
								<view class="label" @tap="mesClick">
									{{ city }}
									<van-icon style="margin: 4rpx 10rpx 0" size="10px" name="/static/img/b_xl.png" />
								</view>
								<view class="search_line"></view>
								<view class="search_sc" :style="'padding: ' + (navbar.height - 24) / 2 + 'px'"
									@tap="visitSearch">
									<van-search readonly custom-class="search-round" placeholder="请输入您要搜索的内容"
										placeholder-style="font-size:24rpx" background="#f4f4f4" />
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- #endif -->
			<template v-if="loading == 1">
				<view class="top_banner">
					<view :class="'bg_top ' + (isbgtop ? 'isbgtop' : '')">
						<view v-if="isbgtop" class="bgtop_box">
							<view class="welcome_btn" style="justify-content: space-between">
								<view class="wel_tet" style="font-size: 32rpx">
									<text style="font-size: 44rpx">Hi,</text>
									可居欢迎你！
								</view>
								<view class="zixun_btn">
									咨询了解
									<!-- #ifdef MP-WEIXIN -->
									<button class="poa_btn" open-type="contact" :plain="true"></button>
									<!-- #endif -->
								</view>
							</view>
							<view class="daiyunying">
								<view class="dyy_item">
									<uni-icons type="checkbox" size="12" color="#fff" style="margin-right: 10rpx">
									</uni-icons>
									小红书代运营
								</view>
								<view class="dyy_item">
									<uni-icons type="checkbox" size="12" color="#fff" style="margin-right: 10rpx">
									</uni-icons>
									抖音代运营
								</view>
								<view class="dyy_item">
									<uni-icons type="checkbox" size="12" color="#fff" style="margin-right: 10rpx">
									</uni-icons>
									Ai云监管
								</view>
							</view>
							<view class="notice" style="margin-top: 40rpx;">
								<view class="label">
									<image src="/static/img/gg.png"
										style="height: 32rpx; width: 32rpx; margin-right: 14rpx" mode="widthFix" />
									<view class="item">平台公告</view>
								</view>
								<view class="list">
									<swiper interval="3000" duration="800" :autoplay="true" :circular="true"
										:vertical="true" easing-function="linear">
										<block v-for="(item, index) in notice.list" :key="index">
											<swiper-item @touchmove.stop.prevent="noSwiping">
												<navigator hover-class="none"
													:url="$com.links('https://shop.keju123.com/article.aspx$id^' + item.id)">
													<view class="item">{{ item.title }}</view>
												</navigator>
											</swiper-item>
										</block>
									</swiper>
								</view>
							</view>
						</view>
						<view v-else class="bgtop_box">
							<view class="welcome_btn">
								<text style="font-size: 72rpx">Hi,</text>
								<view style="font-size: 44rpx">可居欢迎你！</view>
							</view>
							<view class="notice">
								<view class="label">
									<image src="/static/img/gg.png"
										style="height: 32rpx; width: 32rpx; margin-right: 14rpx" mode="widthFix" />
									<view class="item">平台公告</view>
								</view>
								<view class="list">
									<swiper interval="3000" duration="800" :autoplay="true" :circular="true"
										:vertical="true" easing-function="linear">
										<block v-for="(item, index) in notice.list" :key="index">
											<swiper-item @touchmove.stop.prevent="noSwiping">
												<navigator hover-class="none"
													:url="$com.links('https://shop.keju123.com/article.aspx$id^' + item.id)">
													<view class="item">{{ item.title }}</view>
												</navigator>
											</swiper-item>
										</block>
									</swiper>
								</view>
							</view>
							<view class="daiyunying" style="margin-top: 64rpx; margin-bottom: 28rpx">
								<view class="dyy_item">
									<uni-icons type="checkbox" size="12" color="#fff" style="margin-right: 10rpx">
									</uni-icons>
									小红书代运营
								</view>
								<view class="dyy_item">
									<uni-icons type="checkbox" size="12" color="#fff" style="margin-right: 10rpx">
									</uni-icons>
									抖音代运营
								</view>
								<view class="dyy_item">
									<uni-icons type="checkbox" size="12" color="#fff" style="margin-right: 10rpx">
									</uni-icons>
									Ai云监管
								</view>
							</view>
							<view class="zixun_btn">
								咨询了解
								<!-- #ifdef MP-WEIXIN -->
								<button class="poa_btn" open-type="contact" :plain="true"></button>
								<!-- #endif -->
							</view>
						</view>
					</view>

					<!-- 自定义banner组件 -->
					<view class="card_bg">
						<view class="sw_top">
							<view class="poa_zhaomu">
								<view>免费入驻</view>
								<view class="zm_line"></view>
							</view>
							<view class="poa_ptxx" @tap="pingtai">平台信息</view>
						</view>
						<view class="swp_videbox">
							<my-swiper :swiper="swiper" @updateDot="updateDot" :dots="dots" :diyHeight="'478'">
							</my-swiper>
						</view>
						<view class="cate_box" style="background-color: rgba(0, 0, 0, 0)">
							<view style="position: relative">
								<!-- 站内公告 end -->
								<view class="home_top">
									<block>
										<view class="item" @tap="gocompany">
											<van-icon size="45px" name="/static/images/zxgs.png" />
											<view class="ext">装修公司</view>
										</view>
										<view class="item" @tap="gosheji">
											<van-icon size="45px" name="/static/images/sheji.png" />
											<view class="ext">设计师</view>
										</view>
										<view class="item" @tap="gojiancai">
											<van-icon size="45px" name="/static/images/jiancai.png" />
											<view class="ext">本地商家</view>
										</view>
									</block>
								</view>
								<view class="category">
									<block>
										<view class="item" @tap="gozhuangxiu">
											<van-icon size="28px" name="/static/img/wyzx.png" />
											<view class="ext">我要装修</view>
										</view>
										<!-- #ifdef MP-WEIXIN -->
										<view class="item" @tap="gochoujiang">
											<!-- <van-icon size="28px" name="/static/img/tuangou.png" /> -->
											<view class="img_gif">
												<image class="icon_gif"
													:src="$com.imageOSS('xuqiu/m17404732920007315.gif')"
													mode="aspectFill" />
											</view>
											<view class="ext">抽奖活动</view>
											<view class="poa_icon poa_icon_hot">热门</view>
										</view>
										<!-- #endif -->
										<view class="item" @tap="goActiveShop">
											<!-- <van-icon size="28px" name="/static/img/mendianhd.png" /> -->
											<view class="img_gif">
												<image class="icon_gif" style="width: 60rpx;height: 50rpx;"
													:src="$com.imageOSS('xuqiu/m17404742070007413.gif')"
													mode="aspectFill" />
											</view>
											<view class="ext">到店优惠</view>
										</view>
										<view class="item" @tap="gojiadian">
											<!-- <van-icon size="26px" name="/static/img/jiadian.png" /> -->
											<view class="img_gif">
												<image class="icon_gif" style="width: 58rpx;height: 54rpx;"
													:src="$com.imageOSS('xuqiu/m17404739210006113.gif')"
													mode="aspectFill" />
											</view>
											<view class="ext">家电家装</view>
											<view class="poa_icon poa_icon_zf">政府补贴</view>
										</view>
										<view class="item" @tap="goCouponpro">
											<van-icon size="28px" name="/static/img/couponicon.png" />
											<view class="ext">抵用券</view>
										</view>
									</block>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<!-- <view class="panel" @tap="gotuiguagn"> 推广</view> -->

				<view class="panel" style="margin-top: 20rpx; border-radius: 16rpx; overflow: hidden">
					<view class="botZtList">
						<swiper class="swiper" :autoplay="true" :circular="true" @change="botZtListChange">
							<block v-for="(item, index) in botZtList" :key="index">
								<swiper-item>
									<view :data-url="item.adurl" @tap="golink"
										style="border-radius: 16rpx; overflow: hidden">
										<image :class="hfListIndex === index ? 'active' : ''"
											:src="$com.imageOSS(item.adimg)" mode="aspectFill" />
									</view>
								</swiper-item>
							</block>
						</swiper>
					</view>
				</view>

				<view class="panel_ptbt" v-if="shop_list.length > 0">
					<view class="ptbt_bg">
						<view class="ptbt_top">
							<block v-for="(item, index) in shop_list_top" :key="index">
								<view class="ptbt_item" @tap="gocompanydetail" :data-id="item.ShopId">
									<view :class="'ptbt_item_img ' + (item.VIP > 0 ? '' : 'borr')">
										<view class="ptbt_item_cate" v-if="item.Category != 'null'">{{ item.Category }}
										</view>
										<image
											:style="'width: 100%;height: ' + (item.Category != 'null' ? '106rpx' : '142rpx') + ';'"
											:src="$com.imageOSS(item.picurl)"></image>
										<image src="/static/img/vip-bg.png" v-if="item.VIP > 0" class="img_bgp"></image>
									</view>
									<view class="ptbt_item_name ellipsis">{{ item.ShopName }}</view>
									<view class="item_shop_coupon">
										<view class="coupon_type">抵</view>
										<view class="coupon_price ellipsis">
											满{{ item.coupon.minusprice }}减{{ item.coupon.price }}</view>
									</view>
								</view>
							</block>
						</view>
						<view class="ptbt_bot">
							<block v-for="(item, index) in shop_list_bot" :key="index">
								<view class="sl_bot_item" @tap="gocompanydetail" :data-id="item.ShopId">
									<view :class="'ptbt_item_img ' + (item.VIP > 0 ? '' : 'borr')">
										<view class="ptbt_item_cate" v-if="item.Category != 'null'">{{ item.Category }}
										</view>
										<image
											:style="'width: 100%;height: ' + (item.Category != 'null' ? '74rpx' : '100%') + ';'"
											:src="$com.imageOSS(item.picurl)"></image>
										<image src="/static/img/vip-bg.png" v-if="item.VIP > 0" class="img_bgp"></image>
									</view>
									<view class="ptbt_item_text">
										<view class="ptbt_item_name ellipsis">{{ item.ShopName }}</view>
										<view class="item_shop_coupon">
											<view class="coupon_type">抵</view>
											<view class="coupon_price ellipsis">
												满{{ item.coupon.minusprice }}减{{ item.coupon.price }}</view>
										</view>
									</view>
								</view>
							</block>
						</view>
						<view class="ptbt_btn">
							<view class="pt_button" @tap="goCouponpro">
								立即领取
								<view class="right_icon">
									<uni-icons type="right" size="10" color="#fff" style="margin-bottom: 10rpx;">
									</uni-icons>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view class="panel shop_panel" v-if="discountshoplist.length > 0">
					<view class="shop_p_text" @tap="goActiveShop">
						<image style="width: 100%; height: 100%" class="top_img"
							:src="$com.imageOSS('xuqiu/m17395153890001868.png')"></image>
						<view class="shop_p_cont">
							<view>到店折扣优惠</view>
							<view class="shop_go shop_go_zhe">{{ M }}月活动</view>
						</view>
					</view>
					<view class="pro_p_duct">
						<block v-for="(item, index) in discountshoplist" :key="index">
							<view class="product_item" @tap="gocompanydetail" :data-id="item.ShopId"
								:data-distance="item.distance">
								<view :class="'item_img_p ' + (item.VIP > 0 ? 'item_img_prr' : '')">
									<image style="width: 100%; height: 100%" :src="$com.imageOSS(item.picurl)"></image>
									<image src="/static/img/vip-bg.png" v-if="item.VIP > 0" class="img_bgp"></image>
								</view>
								<view class="item_text_p ellipsis">{{ item.ShopName }}</view>
								<view class="item_coupon_p">
									<image src="/static/img/qiang.png" class="qiang_bg"></image>
									<view class="item_cou_pri">{{ item.discount }}折</view>
								</view>
							</view>
						</block>
					</view>
				</view>

				<view :class="'panel_box ' + (isFixedTop ? 'fixed_stk' : '')"
					:style="'top: ' + (isFixedTop ? navbarInitHeight : 0) + 'px'">
					<view class="panel_stk">
						<view
							style="border-top-left-radius: 10px; border-top-right-radius: 10px;background: linear-gradient(90deg, rgba(233, 195, 146, 0.4), rgba(230, 184, 125, 0.4), rgba(241, 210, 169, 0.4));padding-top: 20rpx;">
							<view style="width:232rpx;height: 46rpx;margin-left: 20rpx;">
								<image style="width: 100%; height: 100%" src="/static/img/loc_shop.png"
									mode="widthFix" />
							</view>
							<view class="kj_drop" v-if="iscityshow">
								<kj-dropdown :value="s_province" :options="province" @change="province_change">
								</kj-dropdown>
								<kj-dropdown :value="s_city" :options="cities" @change="city_change">
								</kj-dropdown>
								<kj-dropdown :value="zoneid" :options="zonelist" @change="zone_change">
								</kj-dropdown>
								<kj-dropdown :value="value1" :options="option1">
								</kj-dropdown>
							</view>
						</view>
					</view>
				</view>

				<view class="shop-list panel pannel_stb"
					:style="'padding-bottom: 200px;margin-top: ' + (isFixedTop ? 30 : 0) + 'rpx;'">
					<!-- 数据列表组件 -->
					<my-goods-list :goodsList="goodsList" :isFixedTop="isFixedTop" @gocompanydetail="gocompanydetail"
						@followClick="followClick"></my-goods-list>
					<!-- 加载loading -->
					<kj-loading ref="kjLoading" :loaddone_rec="loaddone||goodsListPages==0"></kj-loading>
					<!-- 推荐数据列表 -->
					<my-goods-list :goodsList="rec_list" :isFixedTop="isFixedTop" @gocompanydetail="gocompanydetail"
						@followClick="followClick"></my-goods-list>
					<!-- 加载loading -->
					<kj-loading ref="kjLoading" :loadmore="loadmore" :loaddone="loaddone"></kj-loading>
				</view>
			</template>
			<view class="share" :style="tipTopStyle + leftStyle + ';display: ' + (popupShowTip ? 'block' : 'none')"
				@tap="handlePopupShare">
				<image style="width: 163px; height: 45px" mode="aspectFill" src="/static/image/AD2.png" />
			</view>
			<view class="popup" @tap="handlePopupCloseTip">
				<van-popup :show="popupShow1" :custom-style="topStyle + ';transform: translate3d(-50%,0,0)'"
					@click-overlay="handlePopupCloseTip">
					<view class="popup-wrapper">
						<image style="width: 375px; height: 453px" mode="aspectFill" src="/static/image/AD3.png" />
					</view>
				</van-popup>
			</view>
			<!-- 弹出地区选择 -->
			<view class="popup">
				<uni-popup ref="cityRef" background-color="#fff" type="center">
					<view class="popup-wrapper"
						style="background-color: #fff; width: 360px; padding: 30rpx; height: 600px; border-radius: 10rpx">
						<view style="text-align: center; padding-bottom: 30rpx; font-weight: bold">请选择城市</view>
						<view class="kj_drop kj_drop_pop" v-if="iscityshow">
							<kj-dropdown :value="s_province" :options="province" @change="province_change">
							</kj-dropdown>
							<kj-dropdown :value="s_city" :options="cities" @change="city_change">
							</kj-dropdown>
							<kj-dropdown :value="zoneid" :options="zonelist" @change="zone_change">
							</kj-dropdown>
						</view>
						<view class="submit-layer" @click="zoneSubmit">
							<van-button block type="default" color="#232773">
								确定
							</van-button>
						</view>
					</view>
				</uni-popup>
			</view>

			<!-- 平台信息弹窗 -->
			<!-- <view class="popup">
				<uni-popup ref="popupShowRef" background-color="#fff" type="center">
					<view class="popup-wrapper">
						<image class="pop-image" mode="widthFix" style="width: 636rpx"
							:src="$com.imageOSS(popupads[0] && popupads[0].adimg)" />
						<view v-if="popupads[0] && popupads[0].adurl" class="popup_btn" @tap="golink"
							:data-url="popupads[0].adurl">
						</view>
					</view>
					<view class="close_btn" @tap="handlePopupClose">
						<van-icon name="cross" color="#fff" size="20" />
					</view>
				</uni-popup>
			</view> -->
			<view class="popup">
				<uni-popup ref="popupShowRef" background-color="#fff" type="center">
					<view class="popup-wrapper">
						<image class="pop-image" mode="widthFix" style="width: 100vw;"
							:src="$com.imageOSS(popupads[0] && popupads[0].adimg)" />
						<view v-if="popupads[0] && popupads[0].adurl" class="popup_btn_new" @tap="golink"
							:data-url="popupads[0].adurl">
						</view>
						<view class="close_btn_new" @tap="handlePopupClose">
							<van-icon name="cross" color="#fff" size="20" />
						</view>
					</view>
				</uni-popup>
			</view>
		</view>
		<tab-bar ref="tabbar" :tabInd="0" :number="number" :v_count="v_count"></tab-bar>
	</view>
</template>

<script>
	import {
		getImage,
		getPage,
		getTabbar,
		ChatConfig
	} from '../../utils/config';
	import api from '../../utils/api'
	import {
		http,
		storage,
		promisify,
		$toast,
		$loading,
		$query,
	} from '../../utils/utils'
	import wxApi from '../../utils/wxApi'
	import {
		headerInfo,
		menuButton
	} from '../../utils/env'
	let app = getApp()
	let {
		height,
		right,
		menuWidth
	} = headerInfo
	let leftStyle = `right: ${menuWidth / 2 / 2 + right}px`
	let tipTopStyle = `top: ${height}px;`
	let topStyle = `top: ${height + 10}px;`
	export default {
		data() {
			return {
				getImage: getImage,
				getPage: getPage,
				logged: 0,
				loading: 0,
				userId: 0,

				navbar: {
					top: '',
					height: ''
				},

				window: {},
				city: '',
				hfListIndex: 0,
				botZtListIndex: 0,
				timesHours: 0,
				guize: {},
				timesMinute: 0,
				timesSecond: 0,
				goodsNavFix: false,
				goodsNavType: 1,
				goodsList: [],
				goodsListPage: 1,
				goodsListPages: 0,
				loadmore: false,
				loaddone: false,
				rec_list: [],
				rec_pageindex: 0,
				rec_pages: 0,
				rec_loadmore: true,
				rec_loaddone: false,
				popupShow1: false,
				popupShowTip: false,
				showwellcome: false,
				abnor: false,
				tipTopStyle: tipTopStyle,
				leftStyle: leftStyle,
				topStyle: topStyle,
				imgheights: {},
				curBannerHeight: 0,
				curshop: 0,
				value1: 0,
				s_province: 0,
				s_city: 0,

				option1: [{
						text: '离我最近',
						value: 0
					},
					{
						text: '智能排序',
						value: 1
					},
					{
						text: '评分从高到低',
						value: 2
					}
				],

				regionInfo: [],
				province: [],
				cities: [],
				zonelist: [],
				zoneid: 0,
				navbarInitHeight: 0,

				//导航栏高度
				stkInitHeight: 0,

				//吸顶盒子高度
				isFixedTop: false,

				//是否固定顶部
				popupads: [],

				socketOpen: false,

				// WebSocket连接状态
				socketMsgQueue: [],

				// WebSocket消息队列
				manualStop: false,

				shop_list: [],
				shop_list_top: [],
				shop_list_bot: [],
				product_list: [],
				discountshoplist: [],
				M: '',
				swiper: '',

				notice: {
					list: []
				},

				wellcomepic: '',
				HomeActivityTitle: '',
				homeshop: '',
				botZtList: '',
				designers: '',
				property: '',
				pickerArea: false,
				dots: '',
				activedData: '',
				number: 0,
				data: '',
				category: [],
				adurl: '',
				iscityshow: true,
				shop_id: '',
				v_count: 0,
				isbgtop: false,
				socket: null
			}
		},
		onLoad(options) {
			uni.hideTabBar()
			console.log('options==', options);
			setTimeout(() => {
				this.isbgtop = true
			}, 10000);
			var timestamp = Date.parse(new Date());
			var date = new Date(timestamp);
			//获取月份
			var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
			this.M = M
			var _this = this;
			/**
			 * 获取用户信息
			 */
			let logged;
			let userId = '';
			app.globalData
				.getLogin()
				.then((res) => {
					logged = res.code;
					userId = res.data.user.user_id;
					if (res.data.shop) {
						this.shop_id = res.data.shop.ShopId
					}
				})
				.catch((res) => {
					logged = res;
				})
				.finally(() => {
					this.logged = logged
					this.userId = userId
					if (options?.qudao) {
						let arroptions = options.qudao.split('$')
						console.log('arroptions============',arroptions)
						let qudao = arroptions[0];
						let click_id = arroptions[1] || options.clickid;
						storage.set('qudao', qudao);
						storage.set('click_id', click_id);
						http.post(
							api.default, {
								data: {
									action: 'inithome',
									userid: userId,
									qudao,
									click_id: click_id,
								}
							},
							false
						).then((res) => {
							console.log('1005===========res', res);
						});
					} else {
						storage.remove('qudao');
						storage.remove('click_id');
					}
					let parms = {
						action: 'apphome'
					}
					console.log('parms=====parms', parms, this.shop_id)
					if (this.shop_id || this.shop_id === 0) {
						parms.shopid = this.shop_id
					}
					//第一部分数据加载
					http.get(
						api.default, {
							data: parms
						},
						false
					).then((res) => {
						const {
							data
						} = res.data;
						console.log('data.popupads', data);
						this.swiper = data.ban_list
						this.notice = data.noticelist
						this.loading = 1
						this.wellcomepic = data.wellcomepic
						this.showwellcome = data.showwellcome
						this.HomeActivityTitle = data.HomeActivityTitle
						this.homeshop = data.homeshop
						this.botZtList = data.botZtList
						this.designers = data.designers
						this.popupads = data.popupads
						this.v_count = data.v_count || 0
						app.globalData.v_count = this.v_count;
						// #ifdef MP-WEIXIN
						if (this.popupads.length > 0 && this.$refs.popupShowRef) {
							this.$refs.popupShowRef.open()
						}
						// #endif
					});
				});
			uni.getLocation({
				type: 'gcj02',
				success(res) {
					console.log('获取位置成功==========', res);
					storage.set('mylocation', res);
					console.log('获取位置成功==========', uni.getStorageSync('mylocation'));
					//获取设置城市id
					http.post(
						api.default, {
							data: {
								action: 'getzonebylocation',
								location: res.longitude + ',' + res.latitude
							}
						},
						false
					).then((res) => {
						const {
							data
						} = res.data;
						console.log('---------------------', res.data);
						if (data != null) {
							app.globalData.zoneid = data.region_id;
							app.globalData.zone = data;
							var temp = data.region_path.substring(1, data.region_path.length - 1).split(
								',');
							var s_province = parseInt(temp[0]);
							var s_city = 0;
							if (temp.length >= 2) {
								s_city = parseInt(temp[1]);
							}
							var zoneid = 0;
							if (temp.length == 3) {
								zoneid = parseInt(temp[2]);
							}
							_this.city = app.globalData.zone.shortname
							_this.getRegionInfo().then((res) => {
								//地区格式化
								//_this.formatArea();
								let province = [];
								let city1 = [{
									text: '请选择',
									value: 0
								}];
								// console.log('位置---------------', res);
								var zones = [{
									text: '全部',
									value: 0
								}];
								res.forEach((item, index) => {
									province.push({
										text: item.name,
										value: item.id
									});
									if (item.id == s_province) {
										var cities = item.list;
										cities.forEach((c, i) => {
											city1.push({
												text: c.name,
												value: c.id
											});
											if (s_city == c.id) {
												var zonelist = c.list;
												zonelist.forEach((z, j) => {
													zones.push({
														text: z
															.name,
														value: z.id
													});
												});
											}
										});
									}
								});
								_this.s_province = s_province
								_this.cities = city1
								_this.s_city = s_city
								_this.zonelist = zones
								_this.zoneid = zoneid
								_this.iscityshow = false
								_this.$nextTick(() => {
									_this.iscityshow = true
								})
								//请求列表
								console.log('onLoad获取位置内..................s_city=', _this.s_city);
								_this.getActivedList();
								_this.getProductsInfo((res) => {
									_this.goodsList = res.list
									_this.loadmore = false
									if (_this.loaddone || _this.goodsListPages == 0) {
										_this.getRecShopList((res1) => {
											_this.rec_list = res1.list
											_this.rec_loadmore = false
										});
									}
								});
							});
							console.log('globalData-------', app.globalData);
						}
					});
					const latitude = res.latitude;
					const longitude = res.longitude;
					const speed = res.speed;
					const accuracy = res.accuracy;
				},
				fail(res) {
					console.log('位置fail-------', res);
					//请求列表
					_this.getActivedList();
					_this.getProductsInfo((res) => {
						console.log('onLoad位置fail..................getProductsInfo', res.list);
						_this.goodsList = res.list
						_this.loadmore = false
						if (_this.loaddone || _this.goodsListPages == 0) {
							_this.getRecShopList((res1) => {
								_this.rec_list = res1.list
								_thisrec_loadmore = false
							});
						}
					});
				},
				complete(res) {
					console.log('位置complete-------', res);
				}
			});
			this.getRegionInfo().then((res) => {
				//地区格式化
				this.formatArea();
			});
			//if (this.data.city == "")
			if (app.globalData.zone != null) {
				this.city = app.globalData.zone.shortname
			}
			//获取system信息
			promisify(uni.getSystemInfo)().then((res) => {
				//获取右上角胶囊信息
				// #ifdef MP-WEIXIN
				this.navbar = uni.getMenuButtonBoundingClientRect()
				console.log("--------------", this.navbar)
				// #endif

				//获取右上角胶囊信息
				// #ifdef MP-TOUTIAO
				let navbar = uni.getMenuButtonBoundingClientRect()
				let CustomButton = tt.getCustomButtonBoundingClientRect()
				navbar.customWidth = CustomButton.customNavigation.width - 10
				navbar.marginLeft = CustomButton.customNavigation.marginLeft + 5
				this.navbar = navbar
				// #endif

				// #ifdef APP-PLUS
				this.navbar = menuButton
				// #endif
				this.window = res
			});
		},
		/**
		 * 页面滚动函数--监听页面滚动事件
		 */
		onPageScroll(e) {
			var that = this;
			if (that.stkInitHeight == 0) {
				this.getstkboxheight();
			}
			if (that.navbarInitHeight == 0) {
				this.getnavboxheight();
			}
			uni.createSelectorQuery()
				.in(this)
				.select('.pannel_stb')
				.boundingClientRect(function(rect) {
					if (rect && rect.top > 0) {
						// 列表盒子距顶部的高度
						var listInTop = parseInt(rect.top);
						var isSatisfy = listInTop - that.stkInitHeight - that.navbarInitHeight < 0 ? true : false;
						//为了防止不停的setData, 这儿做了一个等式判断。 只有处于吸顶的临界值才会不相等
						if (that.isFixedTop === isSatisfy) {
							return false;
						}
						console.log('listInTop,stkInitHeight,navbarInitHeight', listInTop, that.stkInitHeight, that
							.navbarInitHeight);
						that.isFixedTop = isSatisfy
					}
				})
				.exec();
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {
			let that = this;
			setTimeout(() => {
				if (that.navbarInitHeight == 0) {
					this.getnavboxheight();
				}
				if (that.stkInitHeight == 0) {
					this.getstkboxheight();
				}
			}, 100);
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow(options) {
			app.globalData.getLogin().then((res) => {
				const {
					user
				} = res.data;
				this.userId = user.user_id
				this.v_count = app.globalData.v_count
				if (user.user_id > 0) {
					this.connectWebSocket();
					this.getunreadmsg();
					console.log('yonghuid', user.user_id);
				}
			});
			if (app.globalData.zone) {
				console.log('onShow----------', app.globalData.zone);
				this.getRegionInfo().then((res) => {
					//地区格式化
					//this.formatArea();
					let province = [];
					let city1 = [{
						text: '请选择',
						value: 0
					}];
					var zones = [{
						text: '全部',
						value: 0
					}];
					var temp = app.globalData.zone.region_path.substring(1, app.globalData.zone.region_path
						.length - 1).split(',');
					var s_province = parseInt(temp[0]);
					var s_city = 0;
					if (temp.length >= 2) {
						s_city = parseInt(temp[1]);
					}
					var zoneid = 0;
					if (temp.length == 3) {
						zoneid = parseInt(temp[2]);
					}
					res.forEach((item, index) => {
						province.push({
							text: item.name,
							value: item.id
						});
						if (item.id == s_province) {
							var cities = item.list;
							cities.forEach((c, i) => {
								city1.push({
									text: c.name,
									value: c.id
								});
								if (s_city == c.id) {
									var zonelist = c.list;
									zonelist.forEach((z, j) => {
										zones.push({
											text: z.name,
											value: z.id
										});
									});
								}
							});
						}
					});
					this.province = province
					console.log('s_province===========', s_province)
					this.s_province = s_province
					this.cities = city1
					this.s_city = s_city
					this.zonelist = zones
					this.zoneid = zoneid
					this.getActivedList();
					//加载产品列表
					if (this.goodsList.length == 0) {
						this.goodsListPage = 1
						this.getProductsInfo((res) => {
							console.log(res);
							this.goodsList = res.list
							this.loadmore = false
							if (this.loaddone || this.goodsListPages == 0) {
								this.rec_pageindex = 1
								this.rec_pages = 0
								this.getRecShopList((res1) => {
									this.rec_list = res1.list
									this.rec_loadmore = false
								});
							}
						});
					}
				});
			}
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {
			// #ifdef MP-WEIXIN
			console.log('onHide------------');
			uni.closeSocket();
			// #endif

			// #ifdef MP-TOUTIAO
			this.socket?.close()
			// #endif
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			console.log('离开页面');
			// #ifdef MP-WEIXIN
			uni.closeSocket();
			// #endif

			// #ifdef MP-TOUTIAO
			this.socket?.close()
			// #endif
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {
			uni.showLoading({
				title: '加载中...'
			});
			this.goodsListPage = 1
			//加载产品列表
			this.getProductsInfo((res) => {
				console.log('onPullDownRefresh--------getProductsInfo', res);
				this.goodsList = res.list
				this.loadmore = false
			});
			if (this.loaddone || this.goodsListPages == 0) {
				this.rec_pageindex = 1
				this.rec_pages = 0
				this.getRecShopList((res1) => {
					this.rec_list = res1.list
					this.rec_loadmore = false
				});
			}
			uni.stopPullDownRefresh();
			uni.hideLoading();
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			console.log('到底了');
			let {
				goodsListPage,
				goodsListPages,
				loadmore,
				rec_pageindex,
				rec_pages,
				rec_loadmore
			} = this;
			//未请求完且未在加载中
			console.log('goodsListPages=========', goodsListPages);
			console.log('goodsListPage=========', goodsListPage);
			console.log('loadmore=========', loadmore);
			if (goodsListPages > goodsListPage && !loadmore) {
				goodsListPage++;
				loadmore = false;

				//显示加载效果
				this.goodsListPage = goodsListPage
				this.loadmore = loadmore
				uni.showNavigationBarLoading();

				//请求数据
				this.getProductsInfo((res) => {
					console.log('底部---------getProductsInfo');
					let {
						goodsList
					} = this;
					loadmore = false;
					this.loadmore = loadmore,
						this.goodsList = goodsList.concat(res.list)
					//隐藏加载效果
					uni.hideNavigationBarLoading();
				});
			} else {
				console.log('底部--------rec_pages=', rec_pages);
				console.log('底部------rec_pageindex=', rec_pageindex);
				console.log('底部-------rec_loadmore=', rec_loadmore);
				if (rec_pageindex == 0) {
					rec_loadmore = false;
				}
				if (rec_pages >= rec_pageindex && !rec_loadmore) {
					rec_pageindex++;
					rec_loadmore = true;

					//显示加载效果
					this.rec_pageindex = rec_pageindex
					this.rec_loadmore = rec_loadmore
					uni.showNavigationBarLoading();

					//请求数据
					this.getRecShopList((res) => {
						let {
							rec_list
						} = this;
						rec_loadmore = false;
						this.rec_loadmore = rec_loadmore,
							this.rec_list = rec_list.concat(res.list)
						//隐藏加载效果
						uni.hideNavigationBarLoading();
					});
				}
			}
		},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {
			if (this.data.userId > 0) {
				pageshare += "?pid=" + this.data.userId;
			}
			return {
				title: ``,
				imageUrl: '',
				path: pageshare,
				success: function(res) {
					console.log('分享')
					//$toast(pageshare);
					if (res.errMsg == 'shareAppMessage:ok') { //转发成功
						$toast(pageshare);
						console.log('分享成功')
						if (res.hasOwnProperty('shareTickets')) { //分享到群

						} else { // 分享到个人

						}

					} else { //转发失败
						console.log("分享失败");
					}
				}
			}
		},
		methods: {
			setToggle(property) {
				this[property] = !this[property]
			},

			handleNotouch() {
				return false;
			},

			/**
			 * 获取地区
			 */
			getRegionInfo() {
				return new Promise((resolve) => {
					storage
						.get('regionInfo')
						.then((res) => {
							this.regionInfo = res,
								this.pickerArea = false
							// console.log('getRegionInfo----------', this.regionInfo);
							resolve(res);
						})
						.catch((res) => {
							http.get(
								api.default, {
									data: {
										action: 'district'
									}
								},
								false
							).then((res) => {
								const {
									data
								} = res.data;
								this.regionInfo = data,
									this.pickerArea = false
								storage.set('regionInfo', data);
								resolve(data);
							});
						});
				});
			},

			imageLoad: function(e) {
				//获取图片真实宽度
				var imgwidth = e.detail.width;
				var imgheight = e.detail.height;
				var //宽高比
					ratio = imgwidth / imgheight; //计算的高度值
				var viewHeight = 750 / ratio;
				var imgheight = viewHeight;
				var imgheights = this.imgheights;
				//把每一张图片的对应的高度记录到数组里
				imgheights[e.target.dataset.id] = imgheight;
				this.imgheights = imgheights
			},

			updateDot(data) {
				let dots = data.detail.dots;
				this.dots = dots
			},

			shopchange: function(e) {
				this.curshop = e.detail.current
			},

			handlePopupClose() {
				this.$refs.popupShowRef.close()
			},

			handlePopupShare() {
				this.popupShow1 = true
				this.popupShowTip = false
			},

			handlePopupCloseTip() {
				this.popupShow1 = false
			},

			pingtai() {
				// #ifdef MP-WEIXIN
				this.$refs.popupShowRef.open()
				// #endif
			},

			gocompanydetail(e) {
				console.log('eee', e);
				const data = e.detail.data || e.currentTarget.dataset;
				console.log('data===================', data);
				if (data.id) {
					wxApi.navigateTo(getPage.companydetail, {
						id: data.id,
						distance: data.distance
					});
				}
			},

			goActiveShop() {
				let {
					ID
				} = this.activedData;
				wxApi.navigateTo(getPage.activeShop, {
					aid: ID
				});
			},

			goCouponpro() {
				wxApi.navigateTo(getPage.couponProduct);
			},

			gocompanydetailCur(e) {
				const data = e.currentTarget.dataset;
				if (data.id) {
					wxApi.navigateTo(getPage.companydetail, {
						id: data.id,
						distance: data.distance
					});
				}
			},

			gocompany() {
				wxApi.switchTab('/pages/company/company');
			},

			/**
			 * 密码修改--网络请求
			 */
			zoneSubmit(e) {
				var zoneid = this.zoneid;
				var cityid = this.s_city;
				var provinceid = this.s_province;
				const {
					regionInfo
				} = this;
				if (zoneid > 0 || cityid > 0 || provinceid > 0) {
					app.globalData.zoneid = zoneid ? zoneid : cityid ? cityid : provinceid;
					console.log('zoneSubmit==================zoneid=', app.globalData.zoneid);
					//获取设置城市id
					http.post(
						api.default, {
							data: {
								action: 'getregioninfo',
								id: app.globalData.zoneid
							}
						},
						false
					).then((res) => {
						const {
							data
						} = res.data;
						if (data != null) {
							app.globalData.zone = data;
							if (e != undefined) {
								this.$refs.cityRef.close()
							}
							this.city = app.globalData.zone.shortname
							this.getProductsInfo((res) => {
								this.goodsList = res.list,
									this.loadmore = false
								if (this.loaddone || res.list.length == 0) {
									this.rec_pageindex = 1
									this.rec_pages = 0
									this.getRecShopList((res1) => {
										this.rec_list = res1.list
										this.rec_loadmore = false
									});
								}
							});
							this.getActivedList();
						}
					});
				} else {
					$toast('请选择城市');
				}
			},

			mesClick(e) {
				this.$refs.cityRef.open()
			},

			gochoujiang() {
				wxApi.navigateTo(getPage.choujiang);
			},

			gojiadian() {
				wxApi.navigateTo(getPage.jiadian);
			},

			gojifen(e) {
				const data = e.currentTarget.dataset || e.target.dataset;
				const url = data.url;
				if (url.indexOf('http') > -1) {
					wxApi.navigateTo('/pages/web/web?id=' + url);
				} else {
					wxApi.navigateTo(url);
				}
			},

			/**
			 * swiper 记录当前值
			 */
			hfListChange(e) {
				this.hfListIndex = e.detail.current
			},

			botZtListChange(e) {
				this.botZtListIndex = e.detail.current
			},

			/**
			 * 搜索
			 */
			visitSearch() {
				wxApi.navigateTo(getPage.search);
			},

			gosheji() {
				wxApi.navigateTo('/pages/designer/designer');
			},

			gomdhd() {
				console.log(getPage.mdhd);
				wxApi.redirectTo(getPage.mdhd);
			},

			gozhuangxiu() {
				console.log(getPage.customer);
				wxApi.redirectTo(getPage.mfsheji);
				// wxApi.redirectTo(getPage.mfsj);
			},

			gojiancai() {
				wxApi.navigateTo(getPage.zhucai);
			},
			
			// 测试用
			gotuiguagn(){
				console.log('getPage.tuiguangdy======',getPage.tuiguangdy)
				wxApi.navigateTo(getPage.tuiguangdy,{
					qudao:8,
					clickid:3
				});
			},

			golink(e) {
				console.log('eeeeee', e);
				const data = e.currentTarget.dataset || e.target.dataset;
				//转为小写并去除左右空格
				var str = data.url.toLowerCase();
				if (str != '') {
					if (str.indexOf('https') === 0 || str.indexOf('http') === 0) {
						wxApi.navigateTo('/pages/web/web?id=' + str);
					} else if (str.indexOf('mm://') == 0) {
						var array = str.split('_');
						if (array[0].replace('mm://', '') == 'shop') {
							wxApi.navigateTo(getPage.companydetail, {
								id: array[1]
							});
						}
					} else if (str.indexOf('ym://') == 0) {
						var url = str.replace("ym://", "");
						if (url.indexOf('subpackages') > 0) {
							url = url.replace("subpackages", "subPackages");
						}
						wxApi.navigateTo(url);
					} else {
						wxApi.navigateTo('/pages/goods/goods?id=' + str);
					}
				}
			},

			// 获取活动数据
			getActivedList() {
				let {
					userId,
					s_city,
					zoneid,
					s_province
				} = this;
				var latitude = 0;
				var longitude = 0;
				var mylocation = null;
				if (uni.getStorageSync('mylocation') == '' && app.globalData.zone == null) {
					//wxApi.navigateTo("/pages/location/index");
					this.$refs.cityRef.open()
					return;
				} else if (uni.getStorageSync('mylocation') != '') {
					mylocation = JSON.parse(uni.getStorageSync('mylocation'));
					latitude = mylocation.latitude;
					longitude = mylocation.longitude;
				} else {
					latitude = app.globalData.zone.lat;
					longitude = app.globalData.zone.lng;
				}
				http.post(
					api.default, {
						data: {
							action: 'getactivitydata',
							latitude: latitude,
							longitude: longitude,
							userid: userId,
							cityid: s_city,
							zoneid: zoneid,
							provinceid: s_province
						}
					},
					false
				).then((res) => {
					const {
						data
					} = res.data;
					this.shop_list = data.shoplist
					this.shop_list_top = data.shoplist.slice(0, 3)
					this.shop_list_bot = data.shoplist.slice(3, 5)
					this.discountshoplist = data.discountshoplist
					this.activedData = data.ms || 0
				});
			},

			/**
			 * 获取产品数据
			 */
			getProductsInfo(cb, a = false) {
				let {
					goodsNavType,
					goodsListPage,
					goodsListPages,
					loaddone,
					abnor,
					userId,
					s_city,
					zoneid,
					s_province
				} = this;
				var latitude = 0;
				var longitude = 0;
				var mylocation = null;
				if (uni.getStorageSync('mylocation') == '' && app.globalData.zone == null) {
					//wxApi.navigateTo("/pages/location/index");
					this.$refs.cityRef.open()
					return;
				} else if (uni.getStorageSync('mylocation') != '') {
					mylocation = JSON.parse(uni.getStorageSync('mylocation'));
					latitude = mylocation.latitude;
					longitude = mylocation.longitude;
				} else {
					latitude = app.globalData.zone.lat;
					longitude = app.globalData.zone.lng;
				}
				http.post(
					api.default, {
						data: {
							action: 'GetShopList',
							pagesize: 10,
							pageindex: goodsListPage,
							latitude: latitude,
							longitude: longitude,
							userid: userId,
							cityid: s_city,
							zoneid: zoneid,
							provinceid: s_province,
							pagetype: 'home'
						}
					},
					a
				).then((res) => {
					const {
						data
					} = res.data;
					//是否加载完毕

					if (data.pages == 0) {
						abnor = true;
					} else {
						abnor = false;
					}
					if (goodsListPage == data.pages && !abnor) {
						loaddone = true;
					}
					this.goodsListPages = data.pages
					this.loaddone = loaddone
					this.abnor = abnor
					console.log('getProductsInfo------------', goodsListPages);
					console.log('cb-----------', cb);
					if (cb) {
						cb(data);
					}
				});
			},

			getRecShopList(cb, a = false) {
				let {
					rec_pageindex,
					rec_pages,
					rec_loaddone,
					userId,
					s_city,
					zoneid,
					s_province
				} = this;
				var mylocation = JSON.parse(uni.getStorageSync('mylocation'));
				http.post(
					api.default, {
						data: {
							action: 'GetRecShopList',
							pagesize: 20,
							pageindex: rec_pageindex,
							nocityid: s_city,
							nozoneid: zoneid,
							latitude: mylocation.latitude,
							longitude: mylocation.longitude,
							userid: userId,
							provinceid: s_province,
							pagetype: 'home'
						}
					},
					a
				).then((res) => {
					const {
						data
					} = res.data;
					//是否加载完毕
					if (rec_pageindex == data.pages) {
						rec_loaddone = true;
					}
					this.rec_pages = data.pages
					this.rec_loaddone = rec_loaddone
					if (cb) {
						cb(data);
					}
				});
			},

			/**
			 * 跳转登录
			 */
			goLogin() {
				wxApi.setStartPage();
				wxApi.navigateTo(getPage.login);
			},

			formatArea() {
				let {
					regionInfo,
					province
				} = this;
				province = [];
				console.log('regionInfo----rrrrrrr', regionInfo)
				regionInfo.forEach((item, index) => {
					province.push({
						text: item.name,
						value: item.id
					});
				});
				var cities = regionInfo[0].list;
				var city = [{
					text: '请选择',
					value: 0
				}];
				cities.forEach((c, i) => {
					city.push({
						text: c.name,
						value: c.id
					});
				});
				var zonelist = cities[0].list;
				var zones = [{
					text: '全部',
					value: 0
				}];
				zonelist.forEach((c, i) => {
					zones.push({
						text: c.name,
						value: c.id
					});
				});
				this.province = province
				this.s_province = province[0].value
				this.cities = city
				this.zonelist = zones
				this.zoneid = 0
				console.log('aaaaaaaaaa=========', this.s_province)
			},

			province_change(e) {
				console.log('ooooooooooooooo', e)
				var id = e;
				const {
					regionInfo
				} = this;
				let city = [{
					text: '请选择',
					value: 0
				}];
				var cityname = '';
				regionInfo.forEach((item, index) => {
					if (item.id == id) {
						cityname = item.name.replace('省', '').replace('市', '');
						var cities = item.list;
						cities.forEach((c, i) => {
							city.push({
								text: c.name,
								value: c.id
							});
						});
					}
				});
				this.cities = city
				this.s_city = 0
				this.s_province = id
				this.city = cityname
				this.iscityshow = false
				this.$nextTick(() => {
					this.iscityshow = true
				})
				this.zoneSubmit();
			},

			city_change(e) {
				var cityid = e;
				console.log('city_change-------------', e.detail);
				let zone = [{
					text: '全部',
					value: 0
				}];
				var city = '';
				if (cityid == 0) {
					this.province.forEach((item, index) => {
						if (item.value == this.s_province) {
							city = item.text.replace('省', '').replace('市', '');
						}
					});
				}
				this.regionInfo.forEach((item, index) => {
					if (item.id == parseInt(this.s_province)) {
						var cities = item.list;
						cities.forEach((c, i) => {
							if (c.id == parseInt(cityid)) {
								var c_zone = c.list;
								city = c.name.replace('市', '');
								c_zone.forEach((z, j) => {
									zone.push({
										text: z.name,
										value: z.id
									});
								});
							}
						});
					}
				});
				this.loadmore = false
				this.s_city = cityid
				this.zonelist = zone
				this.city = city
				this.zoneid = 0
				this.goodsListPage = 1
				this.iscityshow = false
				this.$nextTick(() => {
					this.iscityshow = true
				})
				this.zoneSubmit();
			},

			zone_change(e) {
				var zoneid = e;
				var city = this.city;
				if (zoneid > 0) {
					this.zonelist.forEach((item, index) => {
						if (item.value == zoneid) {
							city = item.text.replace('区', '').replace('县', '');
						}
					});
				} else {
					this.cities.forEach((item, index) => {
						if (item.value == this.s_city) {
							city = item.text.replace('市', '');
						}
					});
				}
				this.zoneid = zoneid
				this.city = city
				this.goodsListPage = 1
				console.log('zone_change-------getProductsInfo');
				this.zoneSubmit();
			},

			godesignerdetail(e) {
				const data = e.currentTarget.dataset;
				if (data.id) {
					wxApi.navigateTo(getPage.companydetail, {
						id: data.id
					});
				}
			},

			/**
			 * 关注店铺
			 */
			followClick(event) {
				let {
					isfav,
					ShopId
				} = event.detail;
				var {
					logged,
					userId
				} = this;
				if (logged) {
					http.post(api.default, {
						data: {
							action: 'fav_shop',
							userid: userId,
							shopid: ShopId
						}
					}).then((res) => {
						let {
							errmsg,
							data
						} = res.data;
						$toast(errmsg, {
							icon: 'success'
						});
						// 前端显示跟新收藏状态
						let goodsArr = this.goodsList;
						goodsArr.forEach((item) => {
							if (item.ShopId == ShopId) {
								item.isfav = data;
							}
						});
						this.goodsList = goodsArr
					});
				} else {
					this.goLogin();
				}
			},

			// 获取navbar盒子高度
			getnavboxheight() {
				let that = this;
				uni.createSelectorQuery()
					.in(this)
					.select('.navbar')
					.boundingClientRect(function(rect) {
						if (rect && rect.height > 0) {
							var navbarInitHeight = parseInt(rect.height);
							that.navbarInitHeight = navbarInitHeight
						}
					})
					.exec();
			},

			// 获取粘性盒子高度
			getstkboxheight() {
				let that = this;
				uni.createSelectorQuery()
					.in(this)
					.select('.panel_stk')
					.boundingClientRect(function(rect) {
						if (rect && rect.height > 0) {
							var stkInitHeight = parseInt(rect.height);
							that.stkInitHeight = stkInitHeight
						}
					})
					.exec();
			},

			// 获取未读消息数
			getunreadmsg() {
				http.post(
					api.default, {
						data: {
							action: 'getunreadmsgcount',
							userid: this.userId
						}
					},
					false
				).then((res) => {
					console.log('未读消息=', res);
					console.log('this=', this);
					app.globalData.unReadMsg = res.data.data;
					this.number = res.data.data
				});
			},

			//连接WebSocket服务器
			connectWebSocket: function() {
				var that = this;
				const socket = uni.connectSocket({
					url: ChatConfig.CIM_URI,
					success: function(res) {
						console.log('WebSocket连接成功');
					},
					fail: function(res) {
						console.log('WebSocket连接失败:', res);
					}
				});
				this.socket = socket;

				// #ifdef MP-TOUTIAO
				socket.onOpen(function(res) {
					console.log('WebSocket连接已打开');
					that.socketOpen = true
					for (var i = 0; i < that.socketMsgQueue.length; i++) {
						that.sendSocketMessage(that.socketMsgQueue[i]);
					}
					that.socketMsgQueue = []
					that.innerOnConnectFinished();
				})
				socket.onClose(function(res) {
					console.log('离开页面--------');
					console.log('WebSocket连接已关闭:', res);
					that.socketOpen = false
					// that.innerOnConnectionClosed(res);
				})
				socket.onMessage(function(res) {
					console.log('接收到服务器发送的数据:', res.data);
					that.innerOnMessageReceived(res);
					// var messages = that.data.messages
					// messages.push(res.data)
					// that.setData({
					//   messages: messages,
					//   scrollIntoView: 'message-' + messages.length
					// })
				})
				// #endif

				// #ifdef MP-WEIXIN
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开');
					that.socketOpen = true
					for (var i = 0; i < that.socketMsgQueue.length; i++) {
						that.sendSocketMessage(that.socketMsgQueue[i]);
					}
					that.socketMsgQueue = []
					that.innerOnConnectFinished();
				});
				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败:', res);
				});
				uni.onSocketClose(function(res) {
					console.log('离开页面--------');
					console.log('WebSocket连接已关闭:', res);
					that.socketOpen = false
					// that.innerOnConnectionClosed(res);
				});
				uni.onSocketMessage(function(res) {
					console.log('接收到服务器发送的数据:', res.data);
					that.innerOnMessageReceived(res);
					// var messages = that.data.messages
					// messages.push(res.data)
					// that.setData({
					//   messages: messages,
					//   scrollIntoView: 'message-' + messages.length
					// })
				});
				// #endif
			},

			innerOnConnectFinished: function() {
				let account = '';
				if (account === '' || account === undefined) {
					this.onConnectFinished();
				} else {
					this.bindAccount(account);
				}
			},

			onConnectFinished: function() {
				//获取当前登录用户
				app.globalData.getLogin().then((res) => {
					console.log(res);
					this.bind(res.data.user.user_id);
				});
			},

			bind: function(account) {
				storage.set('account', account);
				let deviceId = ''; //storage.get('deviceId');
				if (deviceId === '' || deviceId === undefined) {
					deviceId = this.generateUUID();
					storage.set('deviceId', deviceId);
				}
				let browser = '微信小程序';
				let body = {};
				body.key = ChatConfig.KEY_CLIENT_BIND;
				body.timestamp = new Date().getTime();
				body.data = {};
				body.data.uid = account;
				body.data.channel = ChatConfig.APP_CHANNEL;
				body.data.appVersion = ChatConfig.APP_VERSION;
				body.data.packageName = ChatConfig.APP_PACKAGE;
				body.data.deviceId = deviceId;
				body.data.deviceName = browser;
				console.log(body);
				this.sendRequest(body);
			},

			sendRequest: function(body) {
				let data = {};
				data.type = ChatConfig.SENT_BODY;
				data.content = JSON.stringify(body);
				this.sendSocketMessage(JSON.stringify(data));
			},

			innerOnMessageReceived(e) {
				console.log(e);
				let data = JSON.parse(e.data);
				let type = data.type;
				let body = data.content;
				if (type === ChatConfig.PING) {
					this.pong();
					return;
				}
				if (type === ChatConfig.MESSAGE) {
					let message = JSON.parse(body);
					this.onInterceptMessageReceived(message);
					return;
				}
				if (type === ChatConfig.REPLY_BODY) {
					let reply = JSON.parse(body);
					/*
					 * 判断是否是握手鉴权失败
					 * 终止后续自动重连
					 */
					if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
						this.manualStop = true
					}
					this.onReplyReceived(reply);
				}
			},

			pong: function() {
				let data = {};
				data.type = ChatConfig.PONG;
				data.content = ChatConfig.PONG_BODY;
				this.sendSocketMessage(JSON.stringify(data));
			},

			onInterceptMessageReceived(message) {
				/*
				 *被强制下线之后，不再继续连接服务端
				 */
				if (message.action === ChatConfig.ACTION_999) {
					this.manualStop = true
				}
				app.globalData.unReadMsg++;
				this.number = app.globalData.unReadMsg
				console.log('++++', app.globalData.unReadMsg);
			},

			onReplyReceived(reply) {
				console.log(reply);
				if (reply.key === ChatConfig.KEY_CLIENT_BIND && reply.code === ChatConfig.CODE_OK) {
					console.log('登录成功');
				}

				/**
				 * 链接鉴权失败
				 */
				if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
					//hideProcess();
					console.log('鉴权失败');
				}
			},

			innerOnConnectionClosed: function(e) {
				var that = this;
				if (!that.manualStop) {
					let time = Math.floor(Math.random() * 16 + 15);
					setTimeout(function() {
						console.log('Socket重新连接');
						that.connectWebSocket(); //重新连接
					}, time);
				}
			},

			generateUUID() {
				let d = new Date().getTime();
				let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					let r = (d + Math.random() * 16) % 16 | 0;
					d = Math.floor(d / 16);
					return (c === 'x' ? r : (r & 3) | 8).toString(16);
				});
				return uuid.replace(/-/g, '');
			},

			// 发送WebSocket消息
			sendSocketMessage: function(message) {
				if (this.socketOpen) {
					// #ifdef MP-TOUTIAO
					this.socket.send({
						data: message
					});
					// #endif
					// #ifdef MP-WEIXIN
					uni.sendSocketMessage({
						data: message
					});
					// #endif
				} else {
					this.socketMsgQueue.push(message);
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import './home.css';
</style>
